package sdk.webview.fmc.com.fmcsdk.check.activity;

import static sdk.webview.fmc.com.fmcsdk.activity.H5Activity.EVENT_BUS_INSPECTION_DOWNLOAD_SUCCESS;
import static sdk.webview.fmc.com.fmcsdk.activity.H5Activity.EVENT_BUS_NOTIFY_H5_BACK;
//import static sdk.webview.fmc.com.fmcsdk.activity.H5Activity.EVENT_BUS_UPKEEP;
//import static sdk.webview.fmc.com.fmcsdk.activity.H5Activity.EVENT_BUS_WORK_ORDER;
import static sdk.webview.fmc.com.fmcsdk.activity.H5Activity.NOTIFY_INSPECION_STATUS;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import sdk.webview.fmc.com.fmcsdk.BaoTipEvent;
import sdk.webview.fmc.com.fmcsdk.R;
import sdk.webview.fmc.com.fmcsdk.activity.CaptureActivity;
import sdk.webview.fmc.com.fmcsdk.activity.H5Activity;
import sdk.webview.fmc.com.fmcsdk.activity.H5ForNfcActivity;
import sdk.webview.fmc.com.fmcsdk.activity.HomeH5Event;
import sdk.webview.fmc.com.fmcsdk.app.FMCApplication;
import sdk.webview.fmc.com.fmcsdk.base.BaseActivity;
import sdk.webview.fmc.com.fmcsdk.base.BindEventBus;
import sdk.webview.fmc.com.fmcsdk.base.UserApi;
import sdk.webview.fmc.com.fmcsdk.bean.DDTypeBean;
import sdk.webview.fmc.com.fmcsdk.bean.GPSBean;
import sdk.webview.fmc.com.fmcsdk.bean.GetManagerBean;
import sdk.webview.fmc.com.fmcsdk.bean.UnCheckPointBean;
import sdk.webview.fmc.com.fmcsdk.bean.User;
import sdk.webview.fmc.com.fmcsdk.check.CacheHelper;
import sdk.webview.fmc.com.fmcsdk.check.NfcCodeEvent;
import sdk.webview.fmc.com.fmcsdk.check.UpdataPoint;
import sdk.webview.fmc.com.fmcsdk.check.adapter.CheckDetailsAdapter;
import sdk.webview.fmc.com.fmcsdk.check.adapter.WorkResuAdapter;
import sdk.webview.fmc.com.fmcsdk.check.bean.ActivityJsonBean;
import sdk.webview.fmc.com.fmcsdk.check.bean.GetDetailsBean;
import sdk.webview.fmc.com.fmcsdk.check.bean.WorkHistoryBean;
import sdk.webview.fmc.com.fmcsdk.check.dialog.BottomPopupWindow;
import sdk.webview.fmc.com.fmcsdk.check.dialog.CenterPopupWindow;
import sdk.webview.fmc.com.fmcsdk.check.dialog.TipCenterToastDialog;
import sdk.webview.fmc.com.fmcsdk.check.interfaces.CheckDetailsView;
import sdk.webview.fmc.com.fmcsdk.check.listener.SelectPauseReasonListener;
import sdk.webview.fmc.com.fmcsdk.check.listener.UpDateStatusEvent;
import sdk.webview.fmc.com.fmcsdk.check.persenter.CheckDetailsPersenter;
import sdk.webview.fmc.com.fmcsdk.db.DatabaseManager;
import sdk.webview.fmc.com.fmcsdk.dialog.CenterTipDialog;
import sdk.webview.fmc.com.fmcsdk.imagepicker.utils.Utils;
import sdk.webview.fmc.com.fmcsdk.service.UpDateH5Event;
import sdk.webview.fmc.com.fmcsdk.util.Constant;
import sdk.webview.fmc.com.fmcsdk.util.GsonUtil;
import sdk.webview.fmc.com.fmcsdk.util.HandleJsEvent;
import sdk.webview.fmc.com.fmcsdk.util.KLog;
import sdk.webview.fmc.com.fmcsdk.util.NetworkUtils;
import sdk.webview.fmc.com.fmcsdk.util.PreferencesHelper;
import sdk.webview.fmc.com.fmcsdk.util.SnackBarUtil;
import sdk.webview.fmc.com.fmcsdk.util.SoftKeyBoardListener;
import sdk.webview.fmc.com.fmcsdk.util.StringUtils;
import sdk.webview.fmc.com.fmcsdk.util.ToastUtils;
import sdk.webview.fmc.com.fmcsdk.util.Url;
import sdk.webview.fmc.com.fmcsdk.util.UserHelper;
import sdk.webview.fmc.com.fmcsdk.util.retrofit2.observer.ResponseTransformer;
import sdk.webview.fmc.com.fmcsdk.util.retrofit2.subscriber.ResponseSubscriber;

@BindEventBus
public class CheckDetailsActivity extends BaseActivity<CheckDetailsView, CheckDetailsPersenter> implements CheckDetailsView {

    private static final Logger log = LoggerFactory.getLogger(CheckDetailsActivity.class);
    private Handler handler = new Handler();

    @SuppressLint("SetTextI18n")
    private Runnable runnable = new Runnable() {

        @Override
        public void run() {
            String patrolInspectionExpired = getResources().getString(R.string.Patrol_inspection_expired);
            String laterTimely = getResources().getString(R.string.Later_timely);
            String nowTimeDHM = Utils.getNowTimeDHM(baseData.getRecord().getExpExpirDate());
            String[] split = nowTimeDHM.split(",");
            String day = TextUtils.equals("0", split[0]) ? "" : split[0] + getResources().getString(R.string.days);
            String hours = TextUtils.equals("0", split[1]) ? "" : split[1] + getResources().getString(R.string.hour);
            String minutes = TextUtils.equals("0", split[2]) ? "" : split[2] + getResources().getString(R.string.minutes);
            tv_time.setText(patrolInspectionExpired + day + hours + minutes + laterTimely);
            handler.postDelayed(this, 4000);
        }
    };


    private static int PEOPLE_SELECT_CODE = 666;
    private CheckDetailsAdapter checkAdapter;
    private DatabaseManager databaseManager;
    private GetDetailsBean baseData;

    private RecyclerView rv_check;
    private ImageView iv_back;
    private LinearLayout ll_person_charge,
            ll_abnormal, ll_missed, ll_uncheck, ll_all, ll_finish, ll_start, ll_current_status,
            ll_complete_status, ll_time, ll_check, ll_leak_detection, ll_root_view;
    private TextView tv_person_charge, tv_abnormal_number, tv_abnormal, tv_missed_number, tv_missed,
            tv_uncheck_number, tv_uncheck, tv_all_number, tv_all, tv_check, tv_back, tv_complete_status,
            tv_show_time, tv_exp_time, tv_time, tv_title, tv_status, tv_name, tv_start, tv_redeploy, tv_finish, tv_code,
            tv_pause, tv_scan_qr, tv_leak_detection_tip;
    private View view_abnormal, view_missed, view_uncheck, view_all;

    private int isShowCheck = -1, readonly = -1;

    private String id = "", h5BackData = "", taskId = "";
    private String managerName, managerId;
    private int position;
    private long leakDetectionNumber = -1l;
    private String lat = "", lon = "", gpsLocDesc = "";

    JSONObject jsonObject = null;
    private String oldWorkId = "";
    private String workId;
    GetDetailsBean.RecordDTO.PointsDTO selectNfcPoint;
    private boolean isCheckTask;  //是否是来自验收的巡检任务
    private boolean isFirst = true;
    private boolean isFromDeviceHealthCard;
    private int scanFrom = 1; //扫码1:item扫码  2：右下角的扫码按钮
    private List<GetDetailsBean.RecordDTO.PointsDTO> listOne = new ArrayList<>();
    private List<GetDetailsBean.RecordDTO.PointsDTO> listTwo = new ArrayList<>();
    private List<GetDetailsBean.RecordDTO.PointsDTO> listThree = new ArrayList<>();
    private List<GetDetailsBean.RecordDTO.PointsDTO> listFour = new ArrayList<>();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_check_details;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        // 在 Activity 的 onCreate() 方法中设置状态栏颜色
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.setStatusBarColor(ContextCompat.getColor(this, R.color.color_DC3C26)); // 设置状态栏颜色
        }

        databaseManager = new DatabaseManager(context);
        id = presenter.getSharedPrefs().getString("id", "");
        taskId = presenter.getSharedPrefs().getString("taskId", "");
        h5BackData = getIntent().getStringExtra("data"); //H5返回的参数
        isFromDeviceHealthCard = getIntent().getBooleanExtra("isFromDeviceHealthCard", false);

        initView();
        initRecycler();
        initListener();
        initData();

        if (isFromDeviceHealthCard) {
            id = getIntent().getStringExtra("id");
            isShowCheck = 1;
            readonly = 1;
        }

        ActivityJsonBean bean = databaseManager.getUserByName(getClass().getSimpleName() + id);

        if (bean != null) {
            if (!TextUtils.isEmpty(bean.getJson())) {
                baseData = GsonUtil.GsonToBean(bean.getJson(), GetDetailsBean.class);
                getDetails(baseData);
                requestApi();
            }
        } else {
            if (!NetworkUtils.isAvailable(context)) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        CenterPopupWindow centerPopupWindow = new CenterPopupWindow(context, R.layout.dialog_content_no_netork);
                        TextView tv_close = centerPopupWindow.getContentView().findViewById(R.id.tv_close);
                        TextView tv_content = centerPopupWindow.getContentView().findViewById(R.id.tv_content);
                        tv_content.setText(getResources().getString(R.string.wuwangkk));
                        tv_close.setOnClickListener(v -> {
                            finish();
                        });
                        centerPopupWindow.show(ll_person_charge);
                    }
                }, 500); // 延迟500毫秒
            } else {
                requestApi();
            }
        }
        KLog.e(GsonUtil.BeanToJson(listOne));
        SoftKeyBoardListener.setListener(CheckDetailsActivity.this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
                if(view_bottom!=null){
                    view_bottom.setVisibility(View.VISIBLE);
                }
                if(view_finish!=null){
                    view_finish.setVisibility(View.VISIBLE);
                }
                if(view_bottom_Sik!=null){
                    view_bottom_Sik.setVisibility(View.VISIBLE);
                }
                KLog.e("show");
            }

            @Override
            public void keyBoardHide(int height) {
                if(view_bottom!=null) {
                    view_bottom.setVisibility(View.GONE);
                }
                if(view_finish!=null){
                    view_finish.setVisibility(View.GONE);
                }
                if(view_bottom_Sik!=null){
                    view_bottom_Sik.setVisibility(View.GONE);
                }
            }
        });

    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
    }

    @SuppressLint("SetTextI18n")
    private void initRecycler() {
        rv_check.setLayoutManager(new LinearLayoutManager(context));
        rv_check.setNestedScrollingEnabled(false);
        checkAdapter = new CheckDetailsAdapter(R.layout.item_check);
        rv_check.setAdapter(checkAdapter);
        checkAdapter.setEmptyView(View.inflate(context, R.layout.layout_empty, null));
        checkAdapter.setOnItemClickListener((adapter, view, position) -> {

            GetDetailsBean.RecordDTO.PointsDTO pointsDTO = checkAdapter.getData().get(position);
            if (!TextUtils.equals(baseData.getRecord().getStatus(), "ING") && !TextUtils.equals(baseData.getRecord().getStatus(), "COMP")
                    && !TextUtils.equals(baseData.getRecord().getStatus(), "INIT") && !TextUtils.equals(baseData.getRecord().getStatus(), "CLOSE")
                    && readonly != 1) {
                ToastUtils.showCustomToast(context, R.mipmap.icon_error, getResources().getString(R.string.The_current_task_has_not_started));
                return;
            }

            if (readonly == 1 || TextUtils.equals(baseData.getRecord().getStatus(), "COMP") || TextUtils.equals(baseData.getRecord().getStatus(), "INIT")
                    || TextUtils.equals(baseData.getRecord().getStatus(), "CLOSE")
                    || (readonly == 1 && TextUtils.equals(baseData.getRecord().getStatus(), "ALLOCATED"))) {
                //进入只读界面
                if (isCheckTask) {  //是从验收单进来的
                    String pointId = pointsDTO.getId();
                    //先拿到点位id
                    for (GetDetailsBean.RecordDTO.PointsDTO point : baseData.getRecord().getPoints()) {
                        if (point.getId().equals(pointId)) {
                            List<GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO> checkList = point.getCheckList();
                            if (!checkList.isEmpty()) {
                                pointsDTO.setCheckList(checkList);
                            }
                            break;
                        }
                    }
                }
                Intent intent = new Intent(context, ReadonlyWorkDetailActivity.class);
                intent.putExtra("pointData", GsonUtil.BeanToJson(pointsDTO));
                startActivity(intent);
                return;
            }
            if (baseData.getRecord().getFixedRoute() == 1) {  //后台设置了按顺序检查
                if (position > 0) {
                    for (int i = position - 1; i >= 0; i--) {
                        GetDetailsBean.RecordDTO.PointsDTO previousItem = checkAdapter.getData().get(i);
                        if (!previousItem.getStatus().equals("3") && previousItem.getIsSkip() != 1) { //既不是已检 又不是跳过 说明就是未检 或者部分已检
                            ToastUtils.showCustomToast(context, R.mipmap.icon_error, getResources().getString(R.string.Current_tasks_must_be_inspected_in_sequence));
                            return;
                        }
                    }


                }

            }
            this.position = position;
            if ((pointsDTO.getMustScan().equals("1") && !CacheHelper.getInstance().getPointScanMarkers(pointsDTO.getId()))
                    //|| (pointsDTO.getIsSkip() == 1 && CacheHelper.getInstance().getPointScanMarkers(pointsDTO.getId()))
                    || (pointsDTO.getMustScan().equals("2") && !CacheHelper.getInstance().getPointScanMarkers(pointsDTO.getId()))) {  //需要扫码
                CenterPopupWindow centerPopupWindow = new CenterPopupWindow(context, R.layout.dialog_center_tip);
                TextView tvContent = centerPopupWindow.getContentView().findViewById(R.id.tv_content);
                centerPopupWindow.getContentView().findViewById(R.id.iv_close).setOnClickListener(v -> {
                    centerPopupWindow.dismiss();
                });
                if (pointsDTO.getMustScan().equals("1")) {
                    tvContent.setText(getResources().getString(R.string.The_inspection_site_must_be_scanned_If_you_cannot_scan_the_code_you_can_choose_to_skip_the_check));
                } else {
                    tvContent.setText(getResources().getString(R.string.need_nfc_scan_qr));
                }

                TextView tvSkip = centerPopupWindow.getContentView().findViewById(R.id.tv_cancel);
                TextView tvScan = centerPopupWindow.getContentView().findViewById(R.id.tv_sure);
                tvSkip.setText(getResources().getString(R.string.Skip));
                if (pointsDTO.getMustScan().equals("1")) {
                    tvScan.setText(getResources().getString(R.string.main_scan));
                } else {
                    tvScan.setText("NFC" + getResources().getString(R.string.main_scan));
                }

                tvSkip.setOnClickListener(view1 -> {
                    centerPopupWindow.dismiss();
                    GetDetailsBean.RecordDTO.PointsDTO item = checkAdapter.getItem(position);
                    showSkipReasonPopup(view1, item);

                });
                tvScan.setOnClickListener(v -> {
                    centerPopupWindow.dismiss();
                    scanFrom = 1;
                    if (pointsDTO.getMustScan().equals("1")) {
                        applyPermissionsScan();
                    } else if (pointsDTO.getMustScan().equals("2")) {
                        selectNfcPoint = pointsDTO;
                        Intent intent = new Intent(context, H5ForNfcActivity.class);
                        intent.putExtra(Constant.SCAN_TO_OPEN_NFC, false);
                        intent.putExtra("from", "details");
                        startActivity(intent);
//                        CenterPopupWindow popupWindow = new CenterPopupWindow(context, R.layout.dialog_content_tip);
//                        TextView tvCon = popupWindow.getContentView().findViewById(R.id.tv_content);
//                        tvCon.setText(context.getResources().getString(R.string.Android_does_not_support_NFC));
//                        ImageView ivClose = popupWindow.getContentView().findViewById(R.id.iv_close);
//                        ivClose.setVisibility(View.INVISIBLE);
//                        TextView tvSure = popupWindow.getContentView().findViewById(R.id.tv_close);
//                        tvSure.setText(context.getResources().getString(R.string.ok));
//                        tvSure.setOnClickListener(view2 -> {
//                            popupWindow.dismiss();
//                        });
//                        popupWindow.show(view);
                    }

                });
                centerPopupWindow.show(view);
            } else {
                Intent intent = new Intent(context, StartWorkActivity.class);
                intent.putExtra("pointId", pointsDTO.getId());
                intent.putExtra("assetId", pointsDTO.getAssetId());
                intent.putExtra("projId", baseData.getRecord().getProjId());
                intent.putExtra("detailId", id);
                context.startActivity(intent);
            }


        });

        checkAdapter.setListener(url -> {
            KLog.e("222222");
            EventBus.getDefault().post(new BaoTipEvent(url));
            Intent intents = new Intent();
            intents.putExtra(Constant.H5_URL, url);
            intents.setClass(context, H5Activity.class);
            Constant.isBao = true;
            intents.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            context.startActivity(intents);
        });
    }

    private void initData() {

        try {
            if (null != h5BackData) {
                jsonObject = new JSONObject(h5BackData);
                if (jsonObject.has("workId")) {
                    workId = jsonObject.getString("workId"); //进行中的单子的ID
                    oldWorkId = workId;
                    sharedPrefs.edit().putString("curWorkid", workId).commit();
                } else {
                    sharedPrefs.edit().putString("curWorkid", "").commit();
                }
                if (jsonObject.has("isShowCheck")) {
                    isShowCheck = jsonObject.getInt("isShowCheck");
                }
                if (jsonObject.has("readonly")) {
                    readonly = jsonObject.getInt("readonly");
                }
            }

        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }

    private void requestApi() {
        if (!NetworkUtils.isAvailable(context)) return;
        presenter.getDetails(id);
        presenter.getResult();
        presenter.getCommonDDListWithString();
        if (FMCApplication.typeMap.isEmpty()) {
            presenter.getCommonDDListWithString();
            presenter.getOperateReportList();

        } else {
            //有值的话 查看是否切换了多语言
            if (FMCApplication.currentLanguageIsChange) {
                Log.e("huohuohuohuohuo++++", "748946d1as6d16a5s1d65as1d6a1sd");
                FMCApplication.typeMap.clear();
                presenter.getCommonDDListWithString();

                FMCApplication.shutDownList.clear();
                presenter.getOperateReportList();

                FMCApplication.currentLanguageIsChange = false;
            }
        }

    }


    private void initView() {
        rv_check = findViewById(R.id.rv_check);
        tv_start = findViewById(R.id.tv_start);
        tv_redeploy = findViewById(R.id.tv_redeploy);
        iv_back = findViewById(R.id.iv_back);
        tv_title = findViewById(R.id.tv_title);
        ll_current_status = findViewById(R.id.ll_current_status);
        tv_time = findViewById(R.id.tv_time);
        tv_status = findViewById(R.id.tv_status);
        tv_exp_time = findViewById(R.id.tv_exp_time);
        tv_name = findViewById(R.id.tv_name);
        tv_code = findViewById(R.id.tv_code);
        ll_start = findViewById(R.id.ll_start);
        tv_finish = findViewById(R.id.tv_finish);
        ll_finish = findViewById(R.id.ll_finish);
        tv_pause = findViewById(R.id.tv_pause);
        tv_scan_qr = findViewById(R.id.tv_scan_qr);
        ll_person_charge = findViewById(R.id.ll_person_charge);
        tv_person_charge = findViewById(R.id.tv_person_charge);
        ll_abnormal = findViewById(R.id.ll_abnormal);
        tv_abnormal_number = findViewById(R.id.tv_abnormal_number);
        tv_abnormal = findViewById(R.id.tv_abnormal);
        view_abnormal = findViewById(R.id.view_abnormal);
        ll_missed = findViewById(R.id.ll_missed);
        tv_missed_number = findViewById(R.id.tv_missed_number);
        tv_missed = findViewById(R.id.tv_missed);
        view_missed = findViewById(R.id.view_missed);
        ll_uncheck = findViewById(R.id.ll_uncheck);
        tv_uncheck_number = findViewById(R.id.tv_uncheck_number);
        tv_uncheck = findViewById(R.id.tv_uncheck);
        view_uncheck = findViewById(R.id.view_uncheck);
        ll_all = findViewById(R.id.ll_all);
        tv_all_number = findViewById(R.id.tv_all_number);
        tv_all = findViewById(R.id.tv_all);
        view_all = findViewById(R.id.view_all);
        ll_check = findViewById(R.id.ll_check);
        tv_check = findViewById(R.id.tv_check);
        tv_back = findViewById(R.id.tv_back);
        ll_complete_status = findViewById(R.id.ll_complete_status);
        tv_complete_status = findViewById(R.id.tv_complete_status);
        ll_time = findViewById(R.id.ll_time);
        tv_show_time = findViewById(R.id.tv_show_time);
        tv_exp_time = findViewById(R.id.tv_exp_time);
        ll_leak_detection = findViewById(R.id.ll_leak_detection);
        tv_leak_detection_tip = findViewById(R.id.tv_leak_detection_tip);
        ll_root_view = findViewById(R.id.ll_root_view);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (Constant.isBao) {
            Constant.isBao = false;
        }
        return super.onKeyDown(keyCode, event);

    }


    private void initListener() {
        iv_back.setOnClickListener(v -> {
            sharedPrefs.edit().putInt("curPage", -1).commit();
            if (Constant.isBao) {
                // EventBus.getDefault().post(new HomeH5Event());
            }
            iv_back.postDelayed(new Runnable() {
                @Override
                public void run() {
                    finish();
                }
            }, 500);

        });
        tv_redeploy.setOnClickListener(v -> {
            if (NetworkUtils.isAvailable(context)) {  //有网
                Intent intent = new Intent(context, PeopleSelectActivity.class);
                intent.putExtra("staffStructureId", baseData.getRecord().getStaffTeamId());
                intent.putExtra("orgType", "2");
                intent.putExtra("projid", baseData.getRecord().getProjId());
                intent.putExtra("baseBizTypeId", baseData.getRecord().getBaseBizTypeId());
                intent.putExtra("id", baseData.getRecord().getId());
                intent.putExtra("planTimeStaffId", baseData.getRecord().getPlanTimeStaffId());
                startActivityForResult(intent, PEOPLE_SELECT_CODE);
            } else {  //没网
                TipCenterToastDialog centerPopupWindow = new TipCenterToastDialog(context, R.layout.dialog_tip_toast);
                centerPopupWindow.show(v);
                new Handler().postDelayed(centerPopupWindow::dismiss, 1500);
            }
        });

        tv_start.setOnClickListener(v -> {
            JSONObject jsonObject = null;
            String changeInspectionStateJson = FMCApplication.changeInspectionStateJson;
            if (!StringUtils.isEmpty(changeInspectionStateJson)) {
                try {
                    jsonObject = new JSONObject(changeInspectionStateJson);
                    String workId = "";
                    String workTaskId = "";
                    String workTaskDesc = "";
                    String workTaskType = "";
                    if (jsonObject.has("workId")) {
                        workId = jsonObject.getString("workId");
                    }

                    if (jsonObject.has("workTaskId")) {
                        workTaskId = jsonObject.getString("workTaskId");
                    }

                    if (jsonObject.has("workTaskDesc")) {
                        workTaskDesc = jsonObject.getString("workTaskDesc");
                    }

                    if (jsonObject.has("workTaskType")) {
                        workTaskType = jsonObject.getString("workTaskType");
                    }


                    FMCApplication.changeInspectionStateJson = "";
                    if (StringUtils.isEmpty(workId)) {
                        //那就是没有进行中的任务
                        getLocation();
                        if (NetworkUtils.isAvailable(context)) {
                            presenter.getSpStatus(baseData.getRecord().getId(), taskId, "START",
                                    "", "", baseData.getRecord().getProjId(), StringUtils.isEmpty(baseData.getRecord().getActStartDate()) ? System.currentTimeMillis() + "" : baseData.getRecord().getActStartDate(), "", "", gpsLocDesc, lat, lon);
                        } else {
                            long ooTime = System.currentTimeMillis();
                            presenter.getSpStatusSave(baseData.getRecord().getId(), taskId, "START",
                                    "", "", baseData.getRecord().getProjId(), StringUtils.isEmpty(baseData.getRecord().getActStartDate()) ? System.currentTimeMillis() + "" : baseData.getRecord().getActStartDate(), "", "", gpsLocDesc, lat, lon, baseData.getRecord().getDescription(), ooTime + "");
                            getSpStatus("START", ooTime);
                            baseData.getRecord().setStatus("ING");
                            baseData.getRecord().setStatusDesc("进行中");
                            getDetails(baseData);
                            if (sharedPrefs.getInt("curPage", -1) == 2) {
                                sharedPrefs.edit().putString("curWorkid", oldWorkId).commit();
                            } else {
                                sharedPrefs.edit().putString("curWorkid", id).commit();
                            }
                        }
                    } else {
                        showHaveHandlerDialog(workTaskDesc, workId, workTaskId, workTaskType);
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

            } else {
                try {
                    jsonObject = new JSONObject(h5BackData);
                    if (jsonObject.has("workId")) {
                        String curWorkid = sharedPrefs.getString("curWorkid", "");//进行中的单子的ID
//                    String workId = jsonObject.getString("workId"); //进行中的单子的ID
                        String workTaskId = jsonObject.getString("workTaskId"); //进行中的单子的taskId
                        String workTaskDesc = jsonObject.getString("workTaskDesc"); // 进行中的单子的描述
                        String workTaskType = jsonObject.getString("workTaskType"); //insp_order为巡检，用于跳转原生巡检页面
                        if (!TextUtils.isEmpty(curWorkid) && !curWorkid.equals(id)) {
                            showHaveHandlerDialog(workTaskDesc, curWorkid, workTaskId, workTaskType);
                        } else {
                            getLocation();
                            if (NetworkUtils.isAvailable(context)) {
                                presenter.getSpStatus(baseData.getRecord().getId(), taskId, "START",
                                        "", "", baseData.getRecord().getProjId(), StringUtils.isEmpty(baseData.getRecord().getActStartDate()) ? System.currentTimeMillis() + "" : baseData.getRecord().getActStartDate(), "", "", gpsLocDesc, lat, lon);
                            } else {
                                Long ooTime = System.currentTimeMillis();
                                presenter.getSpStatusSave(baseData.getRecord().getId(), taskId, "START",
                                        "", "", baseData.getRecord().getProjId(), StringUtils.isEmpty(baseData.getRecord().getActStartDate()) ? System.currentTimeMillis() + "" : baseData.getRecord().getActStartDate(), "", "", gpsLocDesc, lat, lon, baseData.getRecord().getDescription(), ooTime + "");

                                getSpStatus("START", ooTime);
                                baseData.getRecord().setStatus("ING");
                                baseData.getRecord().setStatusDesc("进行中");
                                getDetails(baseData);
                                if (sharedPrefs.getInt("curPage", -1) == 2) {
                                    sharedPrefs.edit().putString("curWorkid", oldWorkId).commit();
                                } else {
                                    sharedPrefs.edit().putString("curWorkid", id).commit();
                                }
                            }
                        }

                    } else {
                        getLocation();
                        if (NetworkUtils.isAvailable(context)) {
                            presenter.getSpStatus(baseData.getRecord().getId(), taskId, "START",
                                    "", "", baseData.getRecord().getProjId(), StringUtils.isEmpty(baseData.getRecord().getActStartDate()) ? System.currentTimeMillis() + "" : baseData.getRecord().getActStartDate(), "", "", gpsLocDesc, lat, lon);
                        } else {
                            long ootime = System.currentTimeMillis();
                            presenter.getSpStatusSave(baseData.getRecord().getId(), taskId, "START",
                                    "", "", baseData.getRecord().getProjId(), StringUtils.isEmpty(baseData.getRecord().getActStartDate()) ? System.currentTimeMillis() + "" : baseData.getRecord().getActStartDate(), "", "", gpsLocDesc, lat, lon, baseData.getRecord().getDescription(), ootime + "");
                            getSpStatus("START", ootime);
                            baseData.getRecord().setStatus("ING");
                            baseData.getRecord().setStatusDesc("进行中");
                            getDetails(baseData);
                        }
                    }
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
            }


        });

        ll_current_status.setOnClickListener(v ->

        {
            if (baseData == null) return;
            OperationHistoryActivity.startActivity(context, id, baseData.getRecord().getProjId());
        });


        ll_abnormal.setOnClickListener(v -> {
            setSelectFromProcessedStyle(tv_abnormal_number, tv_abnormal, view_abnormal);
            checkAdapter.setNewData(listOne);
            rv_check.requestLayout();
        });
        ll_missed.setOnClickListener(v ->

        {
            setSelectFromProcessedStyle(tv_missed_number, tv_missed, view_missed);
            checkAdapter.setNewData(listTwo);
            rv_check.requestLayout();
        });
        ll_uncheck.setOnClickListener(v ->

        {
            setSelectFromProcessedStyle(tv_uncheck_number, tv_uncheck, view_uncheck);
            checkAdapter.setNewData(listThree);
            rv_check.requestLayout();
        });
        ll_all.setOnClickListener(v ->

        {
            setSelectFromProcessedStyle(tv_all_number, tv_all, view_all);
            checkAdapter.setNewData(listFour);
            rv_check.requestLayout();
        });

        //验收按钮
        tv_check.setOnClickListener(this::showAcceptanceCheckDialog);

        tv_back.setOnClickListener(v ->
        {
            finish();
        });

        tv_pause.setOnClickListener(this::showBottomPopupWindow);

        tv_finish.setOnClickListener(v ->
        {
            if (leakDetectionNumber > 0 && listTwo.size() < leakDetectionNumber) {
                ToastUtils.showCustomToast(context, R.mipmap.icon_error, getResources().getString(R.string.not_complete_task, leakDetectionNumber));
                return;
            }
            int partiallyCheckedNum = 0;
            for (int i = 0; i < listOne.size(); i++) {
                if (listOne.get(i).getStatus().equals("2")) {
                    partiallyCheckedNum++;
                    break;
                }
            }
            if (partiallyCheckedNum > 0) {
                ToastUtils.showCustomToast(context, R.mipmap.icon_error, getResources().getString(R.string.Some_checked_cannot_be_submitted));
                return;
            }
            if (NetworkUtils.isAvailable(context)) {
                presenter.getUnCheckPoint(baseData.getRecord().getProjId(), baseData.getRecord().getId());
            } else {
                setOfflineComplete();
            }
            //presenter.getManager(this.baseData.getRecord().getStaffTeamId(), () -> presenter.getUnCheckPoint(baseData.getRecord().getProjId(), baseData.getRecord().getId()));

        });

        tv_scan_qr.setOnClickListener(v -> {
            scanFrom = 2;
            applyPermissionsScan();
        });

    }


    private void setOfflineComplete() {
        //所有点位
        List<GetDetailsBean.RecordDTO.PointsDTO> unPoints = new ArrayList<>();
        for (int i = 0; i < listOne.size(); i++) {
            if (listOne.get(i).getIsSkip() != 1) {
                unPoints.add(listOne.get(i));
            }
        }

        //如果当前有抽检 并且 已检的数量已经达到抽检的标准
        if (leakDetectionNumber != -1 && listTwo.size() >= leakDetectionNumber) {
            showSubmitPopupWindow(tv_finish, 0);
        } else {
            if (!unPoints.isEmpty()) {
                GetDetailsBean.RecordDTO.PointsDTO data = unPoints.get(0);
                String assetDesc = !StringUtils.isEmpty(unPoints.get(0).getAssetDesc()) ? unPoints.get(0).getAssetDesc() : unPoints.get(0).getLocationDesc();
                //如果当前未检点的数量全部数量一样  listOne 未检   listFour 全部
                if (listFour.size() == listOne.size()) {
                    new CenterTipDialog(this, getResources().getString(R.string.no_inspect), getString(R.string.cancel), false, new CenterTipDialog.OnHandlerListener() {
                        @Override
                        public void onHandlerClick() {

                        }

                        @Override
                        public void onNotHandlerClick() {

                        }
                    }).show();
                } else {
                    new CenterTipDialog(this, getResources().getString(R.string.Inspection_point) + assetDesc + getResources().getString(R.string.Not_submitted_for_check), getResources().getString(R.string.Not_process), new CenterTipDialog.OnHandlerListener() {
                        @Override
                        public void onHandlerClick() {
                            Intent intent = new Intent(context, StartWorkActivity.class);
                            intent.putExtra("assetId", data.getAssetId());
                            intent.putExtra("projId", baseData.getRecord().getProjId());
                            intent.putExtra("detailId", id);
                            intent.putExtra("pointId", data.getId());
                            context.startActivity(intent);
                        }

                        @Override
                        public void onNotHandlerClick() {
                            //如果当前有抽检 并且 已检的数量已经达到抽检的标准
                            if (leakDetectionNumber != -1 && listTwo.size() >= leakDetectionNumber) {
                                showSubmitPopupWindow(tv_finish, 0);
                            } else {
                                showSubmitPopupWindow(tv_finish, unPoints.size());
                            }

                        }
                    }).show();
                }
            } else {
                showSubmitPopupWindow(tv_finish, 0);
            }


        }

    }
     private View view_bottom_Sik;
    private void showSkipReasonPopup(View view, GetDetailsBean.RecordDTO.PointsDTO item) {
        BottomPopupWindow bottomPopupWindow = new BottomPopupWindow(context, R.layout.dialog_skip_reason);
        View contentView = bottomPopupWindow.getContentView();
        view_bottom_Sik=contentView.findViewById(R.id.view_bottom);
        TextView tvCancel = contentView.findViewById(R.id.tv_cancel);
        TextView tvSure = contentView.findViewById(R.id.tv_sure);
        EditText et_reason = contentView.findViewById(R.id.et_reason);
        TextView tvFontNumber = contentView.findViewById(R.id.tvFontNumber);
        et_reason.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @SuppressLint("SetTextI18n")
            @Override
            public void afterTextChanged(Editable s) {
                tvFontNumber.setText(s.length() + "/" + "100");
                if (s.length() > 100) {
                    s.delete(100, s.length());
                }
            }
        });

        tvCancel.setOnClickListener(v -> {
            bottomPopupWindow.dismiss();
        });
        tvSure.setOnClickListener(v -> {
            if (StringUtils.isEmpty(et_reason.getText().toString())) {
                ToastUtils.showCustomToast(context, R.mipmap.icon_error, context.getResources().getString(R.string.Please_enter_remarks));
                return;
            }
            item.setIsSkip(1);
            item.setStatus("1");
            updatePoint(item, et_reason.getText().toString());
            bottomPopupWindow.dismiss();
        });

        bottomPopupWindow.show(view);
    }

    private void showHaveHandlerDialog(String msg, String workId, String workTaskId, String workTaskType) {
        String haveHandler = getResources().getString(R.string.You_have_a_task_in_progress);
        String toHandler = getResources().getString(R.string.To_handle);
        CenterTipDialog centerTipDialog = new CenterTipDialog(context, haveHandler + msg + toHandler + "?", null, new CenterTipDialog.OnHandlerListener() {
            @Override
            public void onHandlerClick() {
                presenter.getSharedPrefs().edit().putString("id", workId).apply();
                presenter.getSharedPrefs().edit().putString("taskId", workTaskId).apply();
                if (workTaskType.equals("insp_order")) { //跳转到巡检原生
                    sharedPrefs.edit().putInt("curPage", 2).commit();
                    startActivity(context, h5BackData);
                } else {
                    String h5Url = "";
                    String baseUrl = PreferenceManager.getDefaultSharedPreferences(context).getString(Constant.BASE_ADDRESS_URL, "");
                    if (workTaskType.equals("pm_order")) { //跳转至保养
                        h5Url = baseUrl + "/h5/mytask/?accessToken=" + UserHelper.getToken() + "#/pmtask/read/" + workId + "/" + workTaskId;
                    } else {  //跳转至工单
                        h5Url = baseUrl + "/h5/mytask/?accessToken=" + UserHelper.getToken() + "#/srtask/detail/" + workId + "/" + workTaskId + "?from=app";
                    }
                    EventBus.getDefault().post(new BaoTipEvent(h5Url));
                    Intent intents = new Intent();
                    intents.putExtra(Constant.H5_URL, h5Url);
                    intents.setClass(context, H5Activity.class);
                    Constant.isBao = true;
                    intents.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                    context.startActivity(intents);
                }

//                if (null != centerTipDialog && centerTipDialog.isShowing()){
//                    centerTipDialog.dismiss();
//                }

            }

            @Override
            public void onNotHandlerClick() {

            }
        });
        centerTipDialog.show();
    }

    private void applyPermissionsScan() {
        if (Build.VERSION.SDK_INT >= 23) {
            List<String> permissionLists = new ArrayList<>();
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                permissionLists.add(Manifest.permission.CAMERA);
            }

            if (!permissionLists.isEmpty()) {//说明肯定有拒绝的权限
                ActivityCompat.requestPermissions(this, permissionLists.toArray(new String[0]), 4);
                snackbar = SnackBarUtil.show(this, "获取相机权限说明：", "用于扫描位置码或者设备码");
            } else {
                Intent intent = new Intent(context, CaptureActivity.class);
                intent.putExtra("bletooth", "1");
                startActivityForResult(intent, 101);
            }

        }

    }

    private Snackbar snackbar;

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[],
                                           int[] grantResults) {
        if (snackbar != null) {
            snackbar.dismiss();
        }
    }


    private BottomPopupWindow bottomPopupWindowResult;

    private DDTypeBean.RecordsBean recordsData;
    private EditText etOtherRemake;
    private TextView tv_result;

    private void showBottomPopupWindow(View anchor) {
        BottomPopupWindow bottomPopupWindow = new BottomPopupWindow(context, R.layout.dialog_work_pause);
        View view = bottomPopupWindow.getContentView();
        LinearLayout ll_notify_admin = view.findViewById(R.id.ll_notify_admin);
        tv_result = view.findViewById(R.id.tv_result);
        TextView tvWorkGroupPeople = view.findViewById(R.id.tv_work_group_people);
        etOtherRemake = view.findViewById(R.id.et_other_remake);
        CheckBox cb_view = view.findViewById(R.id.cb_view);

        LinearLayout ll_result = view.findViewById(R.id.ll_result);

        if (!StringUtils.isEmpty(managerId) && !managerId.equals(UserHelper.getUserId())) {
            ll_notify_admin.setVisibility(View.VISIBLE);
            tvWorkGroupPeople.setText(managerName);
        } else {
            ll_notify_admin.setVisibility(View.GONE);
        }


        ll_result.setOnClickListener(v -> {
            showBottomPopupWindowResult(tv_pause, recordsBean -> {
                recordsData = recordsBean;
                tv_result.setText(recordsData.getDescription());
                if (recordsData.getCode().equals("5")) { //是其他选项  需要输入备注
                    etOtherRemake.setVisibility(View.VISIBLE);
                } else {
                    etOtherRemake.setVisibility(View.GONE);
                }
            });
        });

        view.findViewById(R.id.tv_cancel).setOnClickListener(v -> {
            bottomPopupWindow.dismiss();
        });
        view.findViewById(R.id.tv_sure).setOnClickListener(v -> {
            if (recordsData == null) {
                ToastUtils.showCustomToast(context, R.mipmap.icon_error, getResources().getString(R.string.Please_fill_in_the_suspension_reason));
                return;
            }

            if (recordsData.getCode().equals("5") && StringUtils.isEmpty(etOtherRemake.getText().toString())) {
                ToastUtils.showCustomToast(context, R.mipmap.icon_error, getResources().getString(R.string.Please_fill_in_the_suspension_reason));
                return;
            }
            getLocation();
            if (NetworkUtils.isAvailable(context)) {
                presenter.getSpStatus(baseData.getRecord().getId(), taskId, "SUSPEND",
                        recordsData.getCode().equals("5") ? etOtherRemake.getText().toString() : tv_result.getText().toString(),
                        recordsData.getCode(), baseData.getRecord().getProjId(),
                        baseData.getRecord().getActStartDate(), recordsData.getType(), cb_view.isChecked() ? managerId : "", gpsLocDesc, lat, lon);
                bottomPopupWindow.dismiss();
            } else {
                Long oooTme = System.currentTimeMillis();
                presenter.getSpStatusSave(baseData.getRecord().getId(), taskId, "SUSPEND",
                        recordsData.getCode().equals("5") ? etOtherRemake.getText().toString() : tv_result.getText().toString(),
                        recordsData.getCode(), baseData.getRecord().getProjId(),
                        baseData.getRecord().getActStartDate(), recordsData.getType(), cb_view.isChecked() ? managerId : "", gpsLocDesc, lat, lon, baseData.getRecord().getDescription(), oooTme + "");
                bottomPopupWindow.dismiss();
                getSpStatus("SUSPEND", oooTme);

                baseData.getRecord().setStatus("SUSPEND");
                baseData.getRecord().setStatusDesc(getString(R.string.zanting));
                getDetails(baseData);
                sharedPrefs.edit().putString("curWorkid", "").commit();
            }

        });


        bottomPopupWindow.show(anchor);
    }


    private void showBottomPopupWindowResult(View anchor, SelectPauseReasonListener listener) {
        if (bottomPopupWindowResult == null) {
            bottomPopupWindowResult = new BottomPopupWindow(CheckDetailsActivity.this, R.layout.dialog_work_pause_result);
            View view = bottomPopupWindowResult.getContentView();
            view.findViewById(R.id.tv_cancel).setOnClickListener(v -> {
                bottomPopupWindowResult.dismiss();
            });
            RecyclerView rv_result = view.findViewById(R.id.rv_result);
            rv_result.setLayoutManager(new LinearLayoutManager(context));
            ActivityJsonBean bean = databaseManager.getUserByName(getClass().getSimpleName() + "result");
            if (bean != null) {
                if (!TextUtils.isEmpty(bean.getJson())) {
                    resultBean = GsonUtil.GsonToBean(bean.getJson(), DDTypeBean.class);
                }
            }
            if (resultBean == null || resultBean.getRecords() == null) return;
            WorkResuAdapter adapter = new WorkResuAdapter(resultBean.getRecords());
            rv_result.setAdapter(adapter);
            adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter a, View view, int position) {
                    KLog.e(position);
                    DDTypeBean.RecordsBean item = (DDTypeBean.RecordsBean) a.getData().get(position);
                    adapter.setSelect(position);
                    listener.selectReasonClick(item);
                    bottomPopupWindowResult.dismiss();
                }
            });

        }
        bottomPopupWindowResult.show(anchor);
    }


    String qaResult = "";
    int ngDispose = -1;
    View view_bottom;
    @SuppressLint("SetTextI18n")
    private void showAcceptanceCheckDialog(View anchor) {
        BottomPopupWindow bottomPopupWindow = new BottomPopupWindow(context, R.layout.dialog_accept_work);
        View view = bottomPopupWindow.getContentView();
        TextView tv_cancel = view.findViewById(R.id.tv_cancel);
         view_bottom=view.findViewById(R.id.view_bottom);
        TextView tv_sure = view.findViewById(R.id.tv_sure);
        CheckBox cb_acceptance = view.findViewById(R.id.cb_acceptance);
        CheckBox cb_acceptance_fails = view.findViewById(R.id.cb_acceptance_fails);
        CheckBox cb_not_accepted = view.findViewById(R.id.cb_not_accepted);
        EditText et_remake = view.findViewById(R.id.et_remake);
        TextView tv_remake_font_number = view.findViewById(R.id.tv_remake_font_number);
        LinearLayout ll_not_go = view.findViewById(R.id.ll_not_go);
        CheckBox cb_create_order = view.findViewById(R.id.cb_create_order);
        CheckBox cb_close_task = view.findViewById(R.id.cb_close_task);
        CheckBox cb_reject_redo = view.findViewById(R.id.cb_reject_redo);
        tv_cancel.setOnClickListener(v -> bottomPopupWindow.dismiss());


        cb_acceptance.setOnCheckedChangeListener((compoundButton, b) -> {
            if (b) {
                cb_acceptance_fails.setChecked(false);
                cb_not_accepted.setChecked(false);
            }
        });

        cb_acceptance_fails.setOnCheckedChangeListener((compoundButton, b) -> {
            if (b) {
                ll_not_go.setVisibility(View.VISIBLE);
                cb_acceptance.setChecked(false);
                cb_not_accepted.setChecked(false);
            } else {
                ll_not_go.setVisibility(View.GONE);
            }
        });

        cb_not_accepted.setOnCheckedChangeListener((compoundButton, b) -> {
            if (b) {
                cb_acceptance.setChecked(false);
                cb_acceptance_fails.setChecked(false);
            }
        });

        cb_create_order.setOnCheckedChangeListener((compoundButton, b) -> {
            if (b) {
                cb_close_task.setChecked(false);
                cb_reject_redo.setChecked(false);
            }
        });

        cb_close_task.setOnCheckedChangeListener((compoundButton, b) -> {
            if (b) {
                cb_create_order.setChecked(false);
                cb_reject_redo.setChecked(false);
            }
        });


        cb_reject_redo.setOnCheckedChangeListener((compoundButton, b) -> {
            if (b) {
                GetDetailsBean.RecordDTO dataRecord = baseData.getRecord();
                if (null != dataRecord && dataRecord.getExpExpirDate() > System.currentTimeMillis()) {
                    cb_create_order.setChecked(false);
                    cb_close_task.setChecked(false);
                } else {
                    cb_reject_redo.setChecked(false);
                }

            }
        });

        et_remake.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }


            @Override
            public void afterTextChanged(Editable editable) {
                tv_remake_font_number.setText(editable.length() + "/" + "100");
                if (editable.length() > 100) {
                    editable.delete(100, editable.length());
                }
            }
        });


        tv_sure.setOnClickListener(v -> {
            if (cb_acceptance.isChecked()) {
                qaResult = "PASS";
            } else if (cb_acceptance_fails.isChecked()) {
                qaResult = "NG";
            } else if (cb_not_accepted.isChecked()) {
                qaResult = "NO";
            } else {
                qaResult = "";
            }

            if (StringUtils.isEmpty(qaResult)) {
                ToastUtils.showCustomToast(context, R.mipmap.icon_error, getResources().getString(R.string.Please_select_acceptance_conclusion));
                return;
            }

            if (qaResult.equals("NG")) {
                if (cb_create_order.isChecked()) {
                    ngDispose = 0;
                } else if (cb_close_task.isChecked()) {
                    ngDispose = 2;
                } else if (cb_reject_redo.isChecked()) {
                    ngDispose = 1;
                } else {
                    ngDispose = -1;
                }

                if (StringUtils.isEmpty(et_remake.getText().toString())) {
                    ToastUtils.showCustomToast(context, R.mipmap.icon_error, getResources().getString(R.string.Please_enter_remarks));
                    return;
                }

                if (ngDispose == -1) {
                    ToastUtils.showCustomToast(context, R.mipmap.icon_error, getResources().getString(R.string.Please_select_acceptance_conclusion));
                    return;
                }
            }

            Map<String, String> map = new HashMap<>();
            map.put("orderId", id);
            map.put("taskId", taskId);
            map.put("qaResult", qaResult);
            map.put("qaRemark", et_remake.getText().toString());
            map.put("ngDispose", ngDispose + "");

            presenter.submitAcceptance(baseData.getRecord().getProjId(), map, () -> {
                if (qaResult.equals("NG") && ngDispose == 0) { //创建整改单
                    String debug = "";
                    if (sharedPrefs.getBoolean(Constant.OPEN_START_MODE, false)) {
                        debug = "&isdebug=true";
                    }
                    String baseUrl = PreferenceManager.getDefaultSharedPreferences(context).getString(Constant.BASE_ADDRESS_URL, "");
                    String h5Url = baseUrl + "/h5/mytask/" + "?accessToken=" + UserHelper.getToken() + debug + "#/srtask/reformorder?fromOrderId=" + baseData.getRecord().getId() +
                            "&questionDesc=" + getResources().getString(R.string.Acceptance_fails_other) + et_remake.getText().toString() + ","
                            + getResources().getString(R.string.Original_task) + (StringUtils.isEmpty(baseData.getRecord().getDescription()) ? "" : baseData.getRecord().getDescription()) +
                            "&projId=" + baseData.getRecord().getProjId() +
                            "&requireType=SR&requestWay=INSP_REFORM&backRepair=2&baseBizTypeId=" + (StringUtils.isEmpty(baseData.getRecord().getBaseBizTypeId()) ? "" : baseData.getRecord().getBaseBizTypeId()) +
                            "&workerId=" + (StringUtils.isEmpty(baseData.getRecord().getPrincipalId()) ? "" : baseData.getRecord().getPrincipalId()) +
                            "&workerDesc=" + (StringUtils.isEmpty(baseData.getRecord().getPrincipalDesc()) ? "" : baseData.getRecord().getPrincipalDesc()) +
                            "&staffTeamId=" + (StringUtils.isEmpty(baseData.getRecord().getStaffTeamId()) ? "" : baseData.getRecord().getStaffTeamId()) +
                            "&from=app&locationDesc=" + (StringUtils.isEmpty(baseData.getRecord().getDescription()) ? "" : baseData.getRecord().getDescription());
                    KLog.e("huohuohuohuo", h5Url);
                    EventBus.getDefault().post(new BaoTipEvent(h5Url));
                    Intent intents = new Intent();
                    intents.putExtra(Constant.H5_URL, h5Url);
                    intents.setClass(context, H5Activity.class);
                    Constant.isBao = true;
                    intents.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                    context.startActivity(intents);
                }
                bottomPopupWindow.dismiss();
                finish();
            });
        });
        bottomPopupWindow.show(anchor);
    }

    public static void startActivity(Context context, String data) {
        Intent intent = new Intent(context, CheckDetailsActivity.class);
        intent.putExtra("data", data);
        context.startActivity(intent);
    }


    private void setSelectFromProcessedStyle(TextView tvNumber, TextView tvName, View view) {
        tv_abnormal_number.setTextColor(getResources().getColor(R.color.color_393A42));
        tv_abnormal.setTextColor(getResources().getColor(R.color.color_393A42));
        tv_missed_number.setTextColor(getResources().getColor(R.color.color_393A42));
        tv_missed.setTextColor(getResources().getColor(R.color.color_393A42));
        tv_uncheck_number.setTextColor(getResources().getColor(R.color.color_393A42));
        tv_uncheck.setTextColor(getResources().getColor(R.color.color_393A42));
        tv_all_number.setTextColor(getResources().getColor(R.color.color_393A42));
        tv_all.setTextColor(getResources().getColor(R.color.color_393A42));
        view_abnormal.setVisibility(View.INVISIBLE);
        view_missed.setVisibility(View.INVISIBLE);
        view_uncheck.setVisibility(View.INVISIBLE);
        view_all.setVisibility(View.INVISIBLE);
        tvNumber.setTextColor(getResources().getColor(R.color.color_DC3C26));
        tvName.setTextColor(getResources().getColor(R.color.color_DC3C26));
        view.setVisibility(View.VISIBLE);
    }

    @Override
    protected CheckDetailsPersenter createPresenter() {
        return new CheckDetailsPersenter();
    }


    @SuppressLint("SetTextI18n")
    public void getDetails(GetDetailsBean baseData) {
        if (NetworkUtils.isAvailable(context)) {
            presenter.getDetailsHistory(id, baseData.getRecord().getProjId());
        }
        presenter.getManager(baseData.getRecord().getStaffTeamId());
        databaseManager.upsertJson(getClass().getSimpleName() + baseData.getRecord().getId(), GsonUtil.BeanToJson(baseData));
        this.baseData = baseData;

        handler.post(runnable);

        if (isFirst) {
            isFirst = false;
            // 延迟显示 PopupWindow
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (baseData.getRecord().getExpExpirDate() < System.currentTimeMillis() && !baseData.getRecord().getStatus().equals("COMP")
                            && !baseData.getRecord().getStatus().equals("CLOSED")) {
                        tv_time.setVisibility(View.GONE);
                        CenterPopupWindow centerPopupWindow = new CenterPopupWindow(context, R.layout.dialog_content_tip);
                        TextView tvContent = centerPopupWindow.getContentView().findViewById(R.id.tv_content);
                        tvContent.setText(getResources().getString(R.string.The_current_inspection_task_has_expired));
                        ImageView ivClose = centerPopupWindow.getContentView().findViewById(R.id.iv_close);
                        ivClose.setVisibility(View.INVISIBLE);
                        TextView tvClose = centerPopupWindow.getContentView().findViewById(R.id.tv_close);
                        tvClose.setText(R.string.haodewo);
                        tvClose.setOnClickListener(view -> {
                            finish();
                        });
                        centerPopupWindow.show(ll_root_view);
                    }
                }
            }, 500);  // 延迟1000ms，确保视图初始化完成

        }


        updateUiByStatus();

        EventBus.getDefault().post(new HandleJsEvent(EVENT_BUS_INSPECTION_DOWNLOAD_SUCCESS, ""));

    }

    private void updateUiByStatus() {
        leakDetectionNumber = -1l;
        resetUi(); //重置UI
        GetDetailsBean.RecordDTO dataRecord = baseData.getRecord();
        String status = dataRecord.getStatus();
        tv_name.setText(dataRecord.getDescription());
        tv_code.setText(dataRecord.getWoNo());
        tv_status.setText(dataRecord.getStatusDesc());

        switch (status) {
            case "INIT":  //待派单
                tv_status.setTextColor(Color.parseColor("#FB8852"));
                break;
            case "ALLOCATED": //已分配
                tv_status.setTextColor(Color.parseColor("#FB8852"));
                break;
            case "ING": //进行中
                tv_status.setTextColor(Color.parseColor("#32CB6F"));
                break;
            case "SUSPEND": //暂停
                tv_status.setTextColor(Color.parseColor("#FB8852"));
                break;
            case "COMP": //已完成
                tv_status.setTextColor(Color.parseColor("#32CB6F"));
                tv_time.setVisibility(View.GONE);
                if (handler != null) {
                    handler.removeCallbacks(runnable);
                }
                break;
            case "CLOSED": //已撤单
                tv_status.setTextColor(Color.parseColor("#4F515D"));
                break;
            case "EXPIRED": //已过期
                tv_status.setTextColor(Color.parseColor("#F1484B"));
                tv_time.setVisibility(View.GONE);
                if (handler != null) {
                    handler.removeCallbacks(runnable);
                }
                break;
            case "CANCEL":
                tv_status.setTextColor(Color.parseColor("#4F515D"));
                break;
        }

        if (isShowCheck == 1 || readonly == 1) {
            if (isShowCheck == 1) {
                if (NetworkUtils.isAvailable(context)) {
                    ll_check.setVisibility(View.VISIBLE);
                } else {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            CenterPopupWindow centerPopupWindow = new CenterPopupWindow(context, R.layout.dialog_content_no_netork);
                            TextView tv_close = centerPopupWindow.getContentView().findViewById(R.id.tv_close);
                            TextView tv_content = centerPopupWindow.getContentView().findViewById(R.id.tv_content);
                            tv_content.setText(R.string.dnagqianwu);
                            tv_close.setOnClickListener(v -> {
                                finish();
                            });
                            centerPopupWindow.show(ll_person_charge);
                        }
                    }, 500); // 延迟500毫秒
                }

            }

            if (readonly == 1) {
                ll_start.setVisibility(View.GONE);
                ll_finish.setVisibility(View.GONE);
                ll_check.setVisibility(View.GONE);
            }

            ll_person_charge.setVisibility(View.VISIBLE);
            tv_person_charge.setText(dataRecord.getPrincipalDesc());

            ll_time.setVisibility(View.VISIBLE);
            tv_show_time.setText(getResources().getString(R.string.Expected_start_time));
            tv_exp_time.setText(Utils.getTimeMDHM(dataRecord.getExpStartDate()));

            if (!StringUtils.isEmpty(dataRecord.getCompRemark())) {
                ll_complete_status.setVisibility(View.VISIBLE);
                tv_complete_status.setText(dataRecord.getCompRemark());
            }

            isCheckTask = true;
            isCheckTask(isCheckTask);


        } else {  //待办
            ll_time.setVisibility(View.VISIBLE);
            tv_show_time.setText(getResources().getString(R.string.ExpirationTime));
            tv_exp_time.setText(Utils.getTimeYMDHMS(dataRecord.getExpExpirDate()));

            switch (status) {
                case "ALLOCATED": //已分配
                    ll_start.setVisibility(View.VISIBLE);
                    break;
                case "ING": //进行中
                    ll_finish.setVisibility(View.VISIBLE);
                    break;
                case "SUSPEND": //暂停
                    ll_start.setVisibility(View.VISIBLE);
                    tv_start.setText(getResources().getString(R.string.ContinueWork));
                    break;
            }

            if (!StringUtils.isEmpty(dataRecord.getCheckRange())) {
                String checkRange = dataRecord.getCheckRange();
                int checkRangeInt = Integer.parseInt(checkRange);
                if (checkRangeInt == 2 && dataRecord.getCheckPercent() > 0) { //有抽检
                    ll_leak_detection.setVisibility(View.VISIBLE);
                    double checkPercent = dataRecord.getCheckPercent() / 100;
                    double num = checkPercent * baseData.getRecord().getPoints().size();
                    leakDetectionNumber = new BigDecimal(num).setScale(0, RoundingMode.UP).longValue();
                    tv_leak_detection_tip.setText(getResources().getString(R.string.It_is_not_missed, leakDetectionNumber));
                } else {
                    ll_leak_detection.setVisibility(View.GONE);
                }
            } else {
                ll_leak_detection.setVisibility(View.GONE);
            }
            isCheckTask = false;
            isCheckTask(isCheckTask);

        }


    }


    private void resetUi() {
        ll_person_charge.setVisibility(View.GONE);
        ll_time.setVisibility(View.GONE);
        ll_complete_status.setVisibility(View.GONE);
        ll_start.setVisibility(View.GONE);
        ll_finish.setVisibility(View.GONE);
        ll_check.setVisibility(View.GONE);
    }


    @SuppressLint("SetTextI18n")
    private void isCheckTask(boolean isCheckTask) {  //显示的是验收状态下的列表UI
        if (isCheckTask) {
            presenter.getSelectOrderIdOrderPoint(id, baseData.getRecord().getProjId(), recordsDTO -> {
                listOne.clear();
                listTwo.clear();
                listThree.clear();
                listFour.clear();

                listOne.addAll(recordsDTO.getAbnormalDataList());

                listTwo.addAll(recordsDTO.getMissDataList());
                listThree.addAll(recordsDTO.getNotDataList());
                listFour.addAll(recordsDTO.getAllDataList());

                for (GetDetailsBean.RecordDTO.PointsDTO pointsDTO : listOne) {
                    for (GetDetailsBean.RecordDTO.PointsDTO point : baseData.getRecord().getPoints()) {
                        if (pointsDTO.getId().equals(point.getId())) {
                            pointsDTO.setCheckList(point.getCheckList());
                            break;
                        }
                    }

                }

                for (GetDetailsBean.RecordDTO.PointsDTO pointsDTO : listTwo) {
                    for (GetDetailsBean.RecordDTO.PointsDTO point : baseData.getRecord().getPoints()) {
                        if (pointsDTO.getId().equals(point.getId())) {
                            pointsDTO.setCheckList(point.getCheckList());
                            break;
                        }
                    }

                }


                for (GetDetailsBean.RecordDTO.PointsDTO pointsDTO : listThree) {
                    for (GetDetailsBean.RecordDTO.PointsDTO point : baseData.getRecord().getPoints()) {
                        if (pointsDTO.getId().equals(point.getId())) {
                            pointsDTO.setCheckList(point.getCheckList());
                            break;
                        }
                    }

                }

                for (GetDetailsBean.RecordDTO.PointsDTO pointsDTO : listFour) {
                    for (GetDetailsBean.RecordDTO.PointsDTO point : baseData.getRecord().getPoints()) {
                        if (pointsDTO.getId().equals(point.getId())) {
                            pointsDTO.setCheckList(point.getCheckList());
                            break;
                        }
                    }

                }

                tv_abnormal_number.setText(listOne.size() + "");
                tv_missed_number.setText(listTwo.size() + "");
                tv_uncheck_number.setText(listThree.size() + "");
                tv_all_number.setText(listFour.size() + "");
                tv_abnormal.setText(getResources().getString(R.string.Abnormal_Report));
                tv_missed.setText(getResources().getString(R.string.Missed));
                tv_uncheck.setText(getResources().getString(R.string.unCheck));
                tv_all.setText(getResources().getString(R.string.All));

                if (!listOne.isEmpty()) {
                    setSelectFromProcessedStyle(tv_abnormal_number, tv_abnormal, view_abnormal);
                    checkAdapter.setNewData(listOne);
                } else {
                    setSelectFromProcessedStyle(tv_all_number, tv_all, view_all);
                    checkAdapter.setNewData(listFour);
                }

                checkAdapter.setReadonly(true, baseData, readonly);

            });
        } else {
            listOne.clear();
            listTwo.clear();
            listThree.clear();
            listFour.clear();
            List<GetDetailsBean.RecordDTO.PointsDTO> points = baseData.getRecord().getPoints();
            for (int i = 0; i < points.size(); i++) {
                if (points.get(i).getIsSkip() == 1) {
                    //跳过
                    listThree.add(baseData.getRecord().getPoints().get(i));
                    //跳过的也在未检当中？
                    listOne.add(baseData.getRecord().getPoints().get(i));
                } else if (points.get(i).getStatus().equals("3")) {  //已检
                    //已检
                    listTwo.add(points.get(i));
                } else { //未检
                    listOne.add(baseData.getRecord().getPoints().get(i));
                }
            }
            listFour.addAll(points);
            tv_abnormal_number.setText(listOne.size() + "");
            tv_missed_number.setText(listTwo.size() + "");
            tv_uncheck_number.setText(listThree.size() + "");
            tv_all_number.setText(listFour.size() + "");
            tv_abnormal.setText(getResources().getString(R.string.unCheck));
            tv_missed.setText(getResources().getString(R.string.Inspected));
            tv_uncheck.setText(getResources().getString(R.string.Skip));
            tv_all.setText(getResources().getString(R.string.All));

            setSelectFromProcessedStyle(tv_abnormal_number, tv_abnormal, view_abnormal);
            checkAdapter.setNewData(listOne);

        }

    }

    private void getLocation() {
        String gpsStr = sharedPrefs.getString(Constant.LON_LAT_DESC, "");
        if (!StringUtils.isEmpty(gpsStr)) {
            GPSBean gpsBean = GsonUtil.GsonToBean(gpsStr, GPSBean.class);
            lat = gpsBean.sLat;
            lon = gpsBean.sLon;
            gpsLocDesc = gpsBean.Position;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(String str) {
        if (str.equals("refresh")) {
            requestApi();
        }

    }

    private DDTypeBean resultBean;


    @Override
    public void getResult(DDTypeBean bean) {
        databaseManager.upsertJson(getClass().getSimpleName() + "result", GsonUtil.BeanToJson(bean));
        this.resultBean = bean;
    }

    @Override
    public void getSpStatus(String orderOperate, long ooTime) {
        requestApi();
        String params = "";
        //通知H5当前任务的状态
        if (orderOperate.equals("START")) { //开始
            params = id + "," + taskId + "," + "1";
            EventBus.getDefault().post(new HandleJsEvent(NOTIFY_INSPECION_STATUS, params));
            if (sharedPrefs.getInt("curPage", -1) == 2) {
                sharedPrefs.edit().putString("curWorkid", oldWorkId).commit();
                Log.e("shuchang", "设置curWorkid4----null---" + oldWorkId);
            } else {
                sharedPrefs.edit().putString("curWorkid", "").commit();
                Log.e("shuchang", "设置curWorkid5-----null--");
            }
            setStartPauseData(ooTime, "继续工作", "【离线操作】" + tv_start.getText().toString(), "111");

        }

        if (orderOperate.equals("SUSPEND")) { //暂停
            params = id + "," + taskId + "," + "0";
            EventBus.getDefault().post(new HandleJsEvent(NOTIFY_INSPECION_STATUS, params));
            sharedPrefs.edit().putString("curWorkid", "").commit();
            Log.e("shuchang", "设置curWorkid6----null---" + oldWorkId);
            setStartPauseData(ooTime, getString(R.string.zanting), getString(R.string.lixiancaozuo) + tv_result.getText().toString(), "111");


        }
    }

    @Override
    public void getSpStatusFail(String json) {
        //请求失败存入本地
        databaseManager.insertInspectState(json);
    }


    @Override
    public void getManagerSuccess(GetManagerBean.RecordBean recordBean) {
        managerName = recordBean.getUserName();
        managerId = recordBean.getId();
    }

    @Override
    public void getUnCheckPointSuccess(List<UnCheckPointBean.RecordBean> recordBean) {
        if (!recordBean.isEmpty()) {
            UnCheckPointBean.RecordBean data = recordBean.get(0);
            String assetDesc = !StringUtils.isEmpty(data.getAssetDesc()) ? data.getAssetDesc() : data.getLocationDesc();

            //如果当前有抽检 并且 已检的数量已经达到抽检的标准
            if (leakDetectionNumber != -1 && listTwo.size() >= leakDetectionNumber) {
                showSubmitPopupWindow(tv_finish, 0);
            } else {
                //如果当前未检点的数量和所有的所有一样
                if (listFour.size() == recordBean.size()) {
                    new CenterTipDialog(this, getResources().getString(R.string.no_inspect), getString(R.string.cancel), false, new CenterTipDialog.OnHandlerListener() {
                        @Override
                        public void onHandlerClick() {

                        }

                        @Override
                        public void onNotHandlerClick() {

                        }
                    }).show();
                } else {
                    new CenterTipDialog(this, getResources().getString(R.string.Inspection_point) + assetDesc + getResources().getString(R.string.Not_submitted_for_check), getResources().getString(R.string.Not_process), new CenterTipDialog.OnHandlerListener() {
                        @Override
                        public void onHandlerClick() {
                            Intent intent = new Intent(context, StartWorkActivity.class);
                            intent.putExtra("assetId", data.getAssetId());
                            intent.putExtra("projId", baseData.getRecord().getProjId());
                            intent.putExtra("detailId", id);
                            intent.putExtra("pointId", data.getId());
                            context.startActivity(intent);
                        }

                        @Override
                        public void onNotHandlerClick() {
                            //如果当前有抽检 并且 已检的数量已经达到抽检的标准
                            if (leakDetectionNumber != -1 && listTwo.size() >= leakDetectionNumber) {
                                showSubmitPopupWindow(tv_finish, 0);
                            } else {
                                showSubmitPopupWindow(tv_finish, recordBean.size());
                            }

                        }
                    }).show();
                }
            }

        } else {
            showSubmitPopupWindow(tv_finish, recordBean.size());
        }
    }

    @Override
    public void getCheckCompleteSuccess() {
        String params = id + "," + taskId + "," + "2";
        EventBus.getDefault().post(new HandleJsEvent(NOTIFY_INSPECION_STATUS, params));
        finish();
    }

    private void updatePoint(GetDetailsBean.RecordDTO.PointsDTO pointsDTO, String quRemake) {
        List<GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO> checkList = new ArrayList<>();
        Long actUploadDate = System.currentTimeMillis();
        Long finishDate = System.currentTimeMillis();
        String id = pointsDTO.getId();
        Integer isSkip = pointsDTO.getIsSkip();
        String orderId = pointsDTO.getOrderId();
        String status = pointsDTO.getStatus();

        if (NetworkUtils.isAvailable(context)) {
            presenter.updateInspectionPoint(baseData.getRecord().getProjId(), actUploadDate, checkList, finishDate, id, isSkip, orderId, quRemake, status);
        } else {
            HashMap<String, Object> map = new HashMap<>();
            map.put("actUploadDate", actUploadDate);
            map.put("checkList", checkList);
            map.put("finishDate", finishDate);
            map.put("id", id);
            map.put("isSkip", isSkip);
            map.put("orderId", orderId);
            map.put("remake", quRemake);
            map.put("status", status);
            CacheHelper.getInstance().saveJumpPoint(baseData.getRecord().getId(), GsonUtil.BeanToJson(map), baseData.getRecord().getProjId());

            if (baseData != null) {
                List<GetDetailsBean.RecordDTO.PointsDTO> points = baseData.getRecord().getPoints();
                for (int i = 0; i < points.size(); i++) {
                    if (TextUtils.equals(id, points.get(i).getId())) {
                        KLog.e(points.get(i).getStatus());
                        points.get(i).setIsSkip(1);//3已检11
                        GetDetailsBean.RecordDTO recordDTO = baseData.getRecord();
                        recordDTO.setPoints(points);
                        baseData.setRecord(recordDTO);
                    }
                }
                getDetails(baseData);

            }

        }

    }

    @Override
    public void updatePointSuccess() {
        requestApi();
    }

    @Override
    public void updatePointFail(HashMap<String, Object> map) {
        String json = new Gson().toJson(map);
        databaseManager.insertInspectPoint(json);
    }

    @Override
    public void getHistory(WorkHistoryBean bean, String id, String projId) {
        new DatabaseManager(context).upsertJson("OperationHistoryActivity" + id + projId, GsonUtil.BeanToJson(bean));
    }

private View view_finish;
    @SuppressLint("SetTextI18n")
    private void showSubmitPopupWindow(View anchor, int size) {
        BottomPopupWindow finishWorkDialog = new BottomPopupWindow(context, R.layout.dialog_finish_work);
        View view = finishWorkDialog.getContentView();
        view_finish=view.findViewById(R.id.view_bottom);
        TextView tvManagerName = view.findViewById(R.id.tv_manager_name);
        CheckBox cb_view = view.findViewById(R.id.cb_view);
        TextView tvStartTime = view.findViewById(R.id.tv_start_time);
        TextView tvWorkTime = view.findViewById(R.id.tv_work_time);
        TextView tvLeaveOut = view.findViewById(R.id.tv_leave_out);
        EditText etRemake = view.findViewById(R.id.et_remake);
        TextView tvFontNumber = view.findViewById(R.id.tv_font_number);
        LinearLayout ll_notify_admin = view.findViewById(R.id.ll_notify_admin);
        LinearLayout ll_missing_point = view.findViewById(R.id.ll_missing_point);

        if (!StringUtils.isEmpty(managerId) && !managerId.equals(UserHelper.getUserId())) {
            ll_notify_admin.setVisibility(View.VISIBLE);
            tvManagerName.setText(managerName);
        } else {
            ll_notify_admin.setVisibility(View.GONE);
        }

        tvStartTime.setText(Utils.getTimeYMDHMS(baseData.getRecord().getExpStartDate()));
        if (size > -1) {
            ll_missing_point.setVisibility(View.VISIBLE);
            tvLeaveOut.setText(size + getResources().getString(R.string.a));
        } else {
            ll_missing_point.setVisibility(View.GONE);
        }

        tvWorkTime.setText(getResources().getString(R.string.Zero_hour));
        etRemake.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @SuppressLint("SetTextI18n")
            @Override
            public void afterTextChanged(Editable s) {
                tvFontNumber.setText(s.length() + "/" + "100");
                if (s.length() > 100) {
                    s.delete(100, s.length());
                }
            }
        });
        view.findViewById(R.id.tv_cancel).setOnClickListener(v -> {
            finishWorkDialog.dismiss();
        });
        view.findViewById(R.id.tv_sure).setOnClickListener(v -> {
            if (size > 0) {
                if (etRemake.getText().toString().isEmpty()) {
                    ToastUtils.showCustomToast(context, R.mipmap.icon_error, getResources().getString(R.string.If_the_number_of_omissions_is_greater));
                } else {
                    if (NetworkUtils.isAvailable(context)) {
                        presenter.getCheckComplete(baseData.getRecord().getProjId(), baseData.getRecord().getId(), taskId, etRemake.getText().toString(), System.currentTimeMillis(), cb_view.isChecked() ? managerId : "");
                    } else {
                        CacheHelper.getInstance().addFinish(baseData.getRecord().getProjId(), baseData.getRecord().getId(), id, taskId, etRemake.getText().toString(), System.currentTimeMillis() + "", cb_view.isChecked() ? managerId : "", baseData.getRecord().getDescription());
                        getCheckCompleteSuccess();
                        finish();
                    }
                }
            } else {
                if (NetworkUtils.isAvailable(context)) {
                    presenter.getCheckComplete(baseData.getRecord().getProjId(), baseData.getRecord().getId(), taskId, etRemake.getText().toString().isEmpty() ? "" : etRemake.getText().toString(), System.currentTimeMillis(), cb_view.isChecked() ? managerId : "");
                } else {
                    CacheHelper.getInstance().addFinish(baseData.getRecord().getProjId(), baseData.getRecord().getId(), id, taskId, etRemake.getText().toString().isEmpty() ? "" : etRemake.getText().toString(), System.currentTimeMillis() + "", cb_view.isChecked() ? managerId : "", baseData.getRecord().getDescription());
                    getCheckCompleteSuccess();
                    finish();
                }
            }
        });


        finishWorkDialog.show(anchor);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @androidx.annotation.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PEOPLE_SELECT_CODE) {
                Bundle bundle = data.getExtras();
                if (null != bundle) {
                    boolean isFinish = bundle.getBoolean("isFinish");
                    if (isFinish) {
                        finish();
                    }
                }
            } else if (requestCode == 101) {
                if (data != null) {
                    Bundle bundle = data.getExtras();
                    if (null != bundle) {
                        String result = bundle.getString(CaptureActivity.SCAN_RESULT);
                        if (!StringUtils.isEmpty(result)) {
                            List<GetDetailsBean.RecordDTO.PointsDTO> allList = checkAdapter.getData();
                            String pointId = "";
                            GetDetailsBean.RecordDTO.PointsDTO point = null;
                            if (scanFrom == 1) {  //点击item进来的
                                point = checkAdapter.getData().get(position);
                                if (!StringUtils.isEmpty(point.getAssetId()) && !"0".equals(point.getAssetId())) {
                                    pointId = point.getAssetId();
                                } else {
                                    pointId = point.getLocationId();
                                }

                                if (pointId.equals(result)) {
                                    scanCodeSuccess(point);
                                } else {
                                    ToastUtils.showCustomToast(context, R.mipmap.icon_error, getResources().getString(R.string.Inspection_point_not_matched));
                                }
                            } else { // 右下角扫码按钮进来的
                                if (baseData.getRecord().getFixedRoute() == 1) { //需要按顺序检查
                                    for (GetDetailsBean.RecordDTO.PointsDTO pointsDTO : allList) {
                                        if (!StringUtils.isEmpty(pointsDTO.getAssetId()) && !pointsDTO.getAssetId().equals("0")) {
                                            pointId = pointsDTO.getAssetId();
                                        } else {
                                            pointId = pointsDTO.getLocationId();
                                        }

                                        if (pointsDTO.getIsSkip() != 1 && !pointsDTO.getStatus().equals("3") && !pointsDTO.getStatus().equals("2")) { //当前点位是未检状态
                                            if (!pointId.equals(result)) { //当前点位是未检 扫的码跟当前的点位不匹配
                                                ToastUtils.showCustomToast(context, R.mipmap.icon_error, getResources().getString(R.string.Current_tasks_must_be_inspected_in_sequence));
                                            } else { //是按照顺序执行的  可以进行跳转
                                                scanCodeSuccess(pointsDTO);
                                            }
                                            return;
                                        } else {
                                            if (pointId.equals(result)) {
                                                scanCodeSuccess(pointsDTO);
                                                return;
                                            }
                                        }
                                    }

                                    ToastUtils.showCustomToast(context, R.mipmap.icon_error, getResources().getString(R.string.not_found_inspection_point));
                                } else {  //不按照顺讯检查
                                    for (GetDetailsBean.RecordDTO.PointsDTO pointsDTO : allList) {
                                        if (!StringUtils.isEmpty(pointsDTO.getAssetId()) && !"0".equals(pointsDTO.getAssetId())) {
                                            pointId = pointsDTO.getAssetId();
                                        } else {
                                            pointId = pointsDTO.getLocationId();
                                        }

                                        if (pointId.equals(result)) {
                                            scanCodeSuccess(pointsDTO);
                                            return;
                                        }

                                    }
                                    ToastUtils.showCustomToast(context, R.mipmap.icon_error, getResources().getString(R.string.not_found_inspection_point));
                                }

                            }


                        }
                    }

                }
            }
        }

    }

    private void scanCodeSuccess(GetDetailsBean.RecordDTO.PointsDTO point) {
        CacheHelper.getInstance().putPointScanMarkers(point.getId());
        Intent intent = new Intent(context, StartWorkActivity.class);
        intent.putExtra("assetId", point.getAssetId());
        intent.putExtra("projId", baseData.getRecord().getProjId());
        intent.putExtra("detailId", id);
        intent.putExtra("pointId", point.getId());
        context.startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (handler != null) {
            handler.removeCallbacks(runnable);
        }
        if (Constant.isBao) {
            Constant.isBao = false;
        }

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void NfcCodeEvent(NfcCodeEvent str) {
        if (!TextUtils.equals(str.getFrom(), "details")) return;
        if (str == null || TextUtils.isEmpty(str.getNfcCode())) {
            ToastUtils.showShort(context, getResources().getString(R.string.dianweibuppe));
            return;
        }
        KLog.e(str.getNfcCode());
        startCodeActivity(str.getNfcCode());
    }


    private void startCodeActivity(String result) {

        if (!StringUtils.isEmpty(result)) {
            if (!StringUtils.isEmpty(result)) {
                List<GetDetailsBean.RecordDTO.PointsDTO> allList = checkAdapter.getData();
                String pointId = "";
                GetDetailsBean.RecordDTO.PointsDTO point = null;
                if (scanFrom == 1) {  //点击item进来的
                    point = checkAdapter.getData().get(position);
                    if (!StringUtils.isEmpty(point.getAssetId()) && !"0".equals(point.getAssetId())) {
                        pointId = point.getAssetId();
                    } else {
                        pointId = point.getLocationId();
                    }

                    if (pointId.equals(result)) {
                        scanCodeSuccess(point);
                    } else {
                        ToastUtils.showCustomToast(context, R.mipmap.icon_error, getResources().getString(R.string.Inspection_point_not_matched));
                    }
                } else { // 右下角扫码按钮进来的
                    if (baseData.getRecord().getFixedRoute() == 1) { //需要按顺序检查
                        for (GetDetailsBean.RecordDTO.PointsDTO pointsDTO : allList) {
                            if (!StringUtils.isEmpty(pointsDTO.getAssetId()) && !pointsDTO.getAssetId().equals("0")) {
                                pointId = pointsDTO.getAssetId();
                            } else {
                                pointId = pointsDTO.getLocationId();
                            }

                            if (pointsDTO.getIsSkip() != 1 && !pointsDTO.getStatus().equals("3") && !pointsDTO.getStatus().equals("2")) { //当前点位是未检状态
                                if (!pointId.equals(result)) { //当前点位是未检 扫的码跟当前的点位不匹配
                                    ToastUtils.showCustomToast(context, R.mipmap.icon_error, getResources().getString(R.string.Current_tasks_must_be_inspected_in_sequence));
                                } else { //是按照顺序执行的  可以进行跳转
                                    scanCodeSuccess(pointsDTO);
                                }
                                return;
                            } else {
                                if (pointId.equals(result)) {
                                    scanCodeSuccess(pointsDTO);
                                    return;
                                }
                            }
                        }

                        ToastUtils.showCustomToast(context, R.mipmap.icon_error, getResources().getString(R.string.not_found_inspection_point));
                    } else {  //不按照顺讯检查
                        for (GetDetailsBean.RecordDTO.PointsDTO pointsDTO : allList) {
                            if (!StringUtils.isEmpty(pointsDTO.getAssetId()) && !"0".equals(pointsDTO.getAssetId())) {
                                pointId = pointsDTO.getAssetId();
                            } else {
                                pointId = pointsDTO.getLocationId();
                            }

                            if (pointId.equals(result)) {
                                scanCodeSuccess(pointsDTO);
                                return;
                            }

                        }
                        ToastUtils.showCustomToast(context, R.mipmap.icon_error, getResources().getString(R.string.not_found_inspection_point));
                    }

                }


            }

        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void NfcCodeEvent(UpDateStatusEvent str) {
        KLog.e(GsonUtil.BeanToJson(str));
        ActivityJsonBean base = databaseManager.getUserByName(getClass().getSimpleName() + id);
        if (base != null) {
            if (!TextUtils.isEmpty(base.getJson())) {
                GetDetailsBean getDetailsBean = GsonUtil.GsonToBean(base.getJson(), GetDetailsBean.class);
                if (getDetailsBean != null) {
                    List<GetDetailsBean.RecordDTO.PointsDTO> points = getDetailsBean.getRecord().getPoints();
                    for (int i = 0; i < points.size(); i++) {
                        if (TextUtils.equals(str.getPointId(), points.get(i).getId())) {
                            KLog.e(points.get(i).getStatus());
                            points.get(i).setStatus(str.getStatus());//3已检
                            GetDetailsBean.RecordDTO recordDTO = getDetailsBean.getRecord();
                            recordDTO.setPoints(points);
                            getDetailsBean.setRecord(recordDTO);
                        }
                    }
                    getDetails(getDetailsBean);
                }

            }
        }

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void NfcCodeEvent(UpdataPoint str) {
        ActivityJsonBean base = databaseManager.getUserByName(getClass().getSimpleName() + id);
        if (base != null) {
            if (!TextUtils.isEmpty(base.getJson())) {
                GetDetailsBean getDetailsBean = GsonUtil.GsonToBean(base.getJson(), GetDetailsBean.class);
                if (getDetailsBean != null) {
                    for (int h = 0; h < str.getList().size(); h++) {
                        List<GetDetailsBean.RecordDTO.PointsDTO> points = getDetailsBean.getRecord().getPoints();
                        for (int i = 0; i < points.size(); i++) {
                            if (TextUtils.equals(str.getList().get(h).getPointId(), points.get(i).getId())) {
                                KLog.e(points.get(i).getStatus());
                                points.get(i).setStatus(str.getList().get(h).getStatus());//3已检
                                GetDetailsBean.RecordDTO recordDTO = getDetailsBean.getRecord();
                                recordDTO.setPoints(points);
                                getDetailsBean.setRecord(recordDTO);
                            }
                        }
                        getDetails(getDetailsBean);
                    }

                }
            }

        }

    }

    private void setStartPauseData(long operateDate, String operateTypeDesc, String operateRemark, String name) {
        User user = PreferencesHelper.getData(User.class);
        name = user.getRecord().getUserName();
        ActivityJsonBean bean = new DatabaseManager(context).getUserByName("OperationHistoryActivity" + id + baseData.getRecord().getProjId());
        if (bean != null) {
            if (!TextUtils.isEmpty(bean.getJson())) {
                WorkHistoryBean workHistoryBean = GsonUtil.GsonToBean(bean.getJson(), WorkHistoryBean.class);
                List<WorkHistoryBean.RecordsDTO> records = workHistoryBean.getRecords();
                records.add(new WorkHistoryBean.RecordsDTO(operateDate, operateTypeDesc, operateRemark, name));
                workHistoryBean.setRecords(records);
                KLog.e(GsonUtil.BeanToJson(workHistoryBean));
                KLog.e(id + "---" + baseData.getRecord().getProjId());
                new DatabaseManager(context).upsertJson("OperationHistoryActivity" + id + baseData.getRecord().getProjId(), GsonUtil.BeanToJson(workHistoryBean));
            }
        }
    }
}
